package org.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

// 心跳服务类 用于向myNacos发送心跳请求
public class HeartbeatService {
    @Autowired
    private RegisterService registerService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private CustomConfig customConfig;


    private String NACOS_SERVER_URL;
    private final long HEARTBEAT_INTERVAL = 3000L; // 3秒

    private ServiceInstance serviceInstance;

    //启动定时任务 发送心跳请求  如果心跳失败 会自动注册服务
    @PostConstruct
    public void startHeartbeat() {
        // 这里赋值 因为初始化的是时候可能还没有注入
        NACOS_SERVER_URL = "http://" + customConfig.getServerAddr() + "/nacos/heartbeat";

        // 初始化服务实例
        serviceInstance = new ServiceInstance();
        serviceInstance.setServiceName(customConfig.getServiceName());
        serviceInstance.setIp("127.0.0.1");
        serviceInstance.setPort(customConfig.getPort());


        //TODO 可以@Async 出去 用外部公共线程池
        Executors.newSingleThreadScheduledExecutor()
                .scheduleAtFixedRate(this::sendHeartbeat, HEARTBEAT_INTERVAL, HEARTBEAT_INTERVAL, TimeUnit.MILLISECONDS);
        System.out.println("定时心跳服务启动");
    }

    private void sendHeartbeat() {
        try {

            //这里不打印心跳了 烦死了
            restTemplate.postForObject(NACOS_SERVER_URL, serviceInstance, String.class);
        } catch (Exception e) {
            e.printStackTrace();  // 打印异常
            // 如果心跳失败，则重新注册服务
            registerService.registerService();
            System.out.println("心跳失败， 重新注册");
        }
    }

}
